package com.bobo.auth.common;




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class JWTAuthFilter extends OncePerRequestFilter {
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();//获取请求地址
        if(uri.contains("auth")){//auth下面路径不处理-这个路径用户登录或验证码请求不需要处理
           filterChain.doFilter(request,response);
           return ;//放行
        }

        String token = request.getHeader("token");//从header获取token
        if(JWTUtils.valid(token)){//获取token
            String username =JWTUtils.getUsername(token);
            //获取当前访问用户的权限
            /*List<SimpleGrantedAuthority> listAuth = (List<SimpleGrantedAuthority>)
                    redisTemplate.opsForValue().get("AUTH:" + username);*/
            List<String> authList = Arrays.asList("ROLE_ADMIN", "ROLE_USER");  //usersService.getAuth(sysUser.getId());//获取登录人的权限
            List<SimpleGrantedAuthority> list = authList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());

            //封装authenticationToken 标记该用户已经登录成功
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(username, "",list);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);//登录成功对象存入上下文中
            filterChain.doFilter(request,response);
            return ;
        }
        filterChain.doFilter(request,response);

    }
}
